<?php

namespace app\common\service;

use app\common\model\Margin;

/**
 *
 * Class MarginService
 * @package app\common\service
 */
class MarginService
{
    /**
     * 同意罚款
     * @param $id
     * @param $confirmStatus 1确认 2不同意
     * @param $confirmMemberType
     * @param $memberId
     * @return void
     */
    public function confirm($id, $confirmStatus, $confirmMemberType, $memberId = 0)
    {
        $margin = Margin::where('id', $id)->find();

        if ($margin->confirmStatus != 0) {
            return;
        }

        $margin->confirmStatus = $confirmStatus;
        $margin->confirmMemberType = $confirmMemberType;
        $margin->confirmMemberId = $memberId;
        $margin->confirmTime = time();
        $margin->save();

        // 确认后自动发起转账
        if ($confirmStatus == 1) {
            $this->punish($margin);
        }
    }

    /**
     * 进行处罚
     * @param Margin $margin
     * @return void
     */
    public function punish(Margin $margin)
    {
        $margin->status = 1;
        $margin->save();

        $this->transfer($margin);
    }

    /**
     * 创建罚款转账
     * @param Margin $margin
     * @return void
     */
    private function transfer(Margin $margin)
    {
        $this->createTransferReverse($margin->memberId, PAYMENT_MARGIN, TRANSFER_MARGIN_PUNISH, $margin->total, $margin->describe, $margin->id);
    }

    /**
     * 创建反向转账申请
     * @param $fromId
     * @param $accountType
     * @param $transferType
     * @param $total
     * @param $describe
     * @param $marginId
     * @return void
     */
    private function createTransferReverse($fromId, $accountType, $transferType, $total, $describe, $marginId)
    {

        $payMethod = $accountType;
        $accountNumber = $fromId;

        $append = [
            'marginId' => $marginId,
        ];

        $this->getTransfersServer()->pushTransferFromMember($transferType, $fromId, $payMethod, $accountNumber, $total, $describe, $append);
    }

    private function getTransfersServer(): TransfersServer
    {
        return app(TransfersServer::class);
    }
}
